import dayjs from 'dayjs';

/**
 * 图片文件压缩
 * @param {*} file
 * @return Promise
 */
export const compressImage = (file: File) => {
  return new Promise((resolve: (value: File) => void, reject) => {
    // 判断支不支持FileReader，支持ie10以上
    if (!file || !window.FileReader) {
      return reject();
    }
    if (!/^image/.test(file.type)) {
      return reject();
    }
    // 小于 100 k时不进行压缩
    if (file.size < 100 * 1024) {
      return resolve(file);
    }
    const compress = (img: HTMLImageElement) => {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d') as CanvasRenderingContext2D;
      const initSize = img.src.length;
      let { width, height } = img;
      // 如果图片大于一百万像素，计算压缩比并将大小压至80万以下
      let ratio = (width * height) / 800000;
      if (ratio > 1) {
        ratio = Math.sqrt(ratio);
        width /= ratio;
        height /= ratio;
      }
      canvas.width = width;
      canvas.height = height;
      // 铺底色，手机上无需上传透明底的图片
      ctx.fillStyle = '#fff';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, width, height);

      // 进行压缩
      const ndata = canvas.toDataURL(file.type, 0.8);
      console.log('******压缩前的图片大小******', initSize);
      console.log('******压缩后的图片大小******', ndata.length);
      // console.log('******压缩后的图片base64地址******', ndata);
      return ndata;
    };

    // 创建一个reader
    const reader = new window.FileReader();

    // 将图片转成base64格式
    reader.readAsDataURL(file);
    // 读取成功后的回调
    reader.onloadend = function () {
      const img = new window.Image();
      img.src = this.result as any;
      img.onload = () => {
        const data = compress(img);
        return resolve(dataURItoFile(data, file.name));
      };
    };
  });
};

// base64转成File对象
export const dataURItoFile = (dataurl: string, name: string) => {
  const arr = dataurl.split(',');
  // @ts-ignore
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  const blob = new window.Blob([u8arr], {
    type: mime,
  });
  return new window.File([blob], `${new Date().getTime()}-${name}`, {
    type: mime,
    lastModified: dayjs().valueOf(),
  });
};

/**
 * 图片url转base64，可能存在跨域问题
 * @param {*} url
 * @returns
 */
export const getUrlToBase64 = (url: string) => {
  return new Promise((resolve) => {
    let canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
    img.crossOrigin = 'Anonymous';
    img.src = url;
    img.onload = () => {
      canvas.height = 120;
      canvas.width = 120;
      ctx?.drawImage(img, 0, 0, 120, 120);
      const dataURL = canvas.toDataURL('image/png');
      console.log(dataURL);
      resolve(dataURL);
      canvas = null as any;
    };
  });
};
